# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function

from ..ops import Sum, Ref, Abs, Less, Greater
from ..base import OpsFeature

from .close import Close

class CMO(OpsFeature):
    """Technical Indicator - CMO

    - CZ1 = IF(CLOSE - REF(CLOSE, 1)>0, CLOSE - REF(CLOSE, 1), 0)
    - CZ2 = IF(CLOSE - REF(CLOSE, 1)<0, ABS(CLOSE - REF(CLOSE, 1)), 0)
    - SU = SUM(CZ1, N)
    - SD = SUM(CZ2, N)
    - CMO = (SU - SD) / (SU + SD) * 100
    """
    def __init__(self, feature=None, N=20):
        self.feature = feature or Close()
        self.N = N

    def __str__(self):
        name = type(self).__name__.lower()
        if str(self.feature) != 'close':
            name += '_'+str(self.feature)
        if self.N != 20:
            name += '_'+str(self.N)
        return name
    
    def _load_internal(self, instrument, start_time, end_time, freq):
        diff = self.feature - Ref(self.feature, 1)
        cz1 = Greater(diff, 0)
        cz2 = Abs(Less(diff, 0))
        su = Sum(cz1, self.N)
        sd = Sum(cz2, self.N)
        cmo = (su - sd) / (su + sd) * 100
        return cmo.load(instrument, start_time, end_time, freq)
